package com.github.md11235.ideaproofofwork.startup

import com.github.md11235.ideaproofofwork.util.snapshotCSourceFiles
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectActivity
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.messages.MessageBusConnection

//import com.jetbrains.cidr.lang.workspace.OCWorkspace

class MyCLionStartupActivity : ProjectActivity {
    var msgBusConn: MessageBusConnection? = null
    override suspend fun execute(project: Project) {
        setupFileContentChangeListeners(project)
    }

    private fun setupFileContentChangeListeners(project: Project) {
        msgBusConn = project.messageBus.connect()
        msgBusConn?.subscribe(
            VirtualFileManager.VFS_CHANGES,
            object : BulkFileListener {
                var isMainCFromZeroSize = false
                override fun before(events: MutableList<out VFileEvent>) {
                    for (event in events) {
                        if (event is VFileContentChangeEvent) {
                            val file = event.file
                            if (file.name == "main.c" && file.length == 0L)
                                isMainCFromZeroSize = true
                        }
                    }
                }
                override fun after(events: MutableList<out VFileEvent>) {
                    for (event in events) {
                        if (event is VFileContentChangeEvent) {
                            val file = event.file
                            if (file.name == "main.c" && isMainCFromZeroSize) {
                                handleCFileContentChangeFromZeroSize(project, event)
                            }
                        }
                    }
                }
            }
        )
    }

    private fun handleCFileContentChangeFromZeroSize(project: Project, event: VFileContentChangeEvent) {
        event.file.let { file ->
            when {
                file.name == "main.c" || file.name == "main.cpp" -> {
                    println("Main C/C++ file created: ${file.path}")
                    handleMainFileCreation(project, file)

                    msgBusConn?.disconnect()
                }
                file.extension in setOf("c", "cpp", "cc", "cxx", "c++") -> {
                    println("C/C++ source file created: ${file.name}")
                }
                file.extension in setOf("h", "hpp", "hh", "hxx") -> {
                    println("C/C++ header file created: ${file.name}")
                }
            }
        }
    }

    private fun handleMainFileCreation(project: Project, file: VirtualFile) {
        snapshotCSourceFiles(project)
    }
}